package de.havre.wakeupnas.sync;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Properties;

import sync.Sync;
import de.havre.wakeupnas.Config;
import de.havre.wakeupnas.nas.NasController;

public class SyncProcess extends Thread {

	private NasController controller;

	public SyncProcess(NasController controller) {
		this.controller = controller;
	}

	public void run() {
		try {
			Properties p = Config.getProperties();
			int index = 1;
			String logfolder = (String) Config.getProperties().get("logfolder");
			File f = new File(logfolder);
			if (!f.exists())
			{
				f.mkdir();
			}
			String timestamp = String.format("%1$tY%1$tm%1$td-%1$tH%1$tM%1$tS", Calendar.getInstance(Locale.ENGLISH));
			String logname = logfolder + timestamp+".log";
			
			while (true) {
				
				String source = (String) p.get("task." + index + ".source");
				String target = (String) p.get("task." + index + ".target");
				if (source == null) {
					break;
				}

				List<String> attributes = new ArrayList<String>();
				attributes.add("--nocrc");
				attributes.add("--force");
				attributes.add("--ignorewarnings");
				if ( logname != null)
				{
					attributes.add("--log:"+logname);
					logname=null;
				}
				attributes.add(source);
				attributes.add(target);
				
				attributes.toArray();
				String[] split = attributes.toArray(new String[attributes.size()]);
				    
				Sync.main(split);
				index++;
			}

			controller.notifySyncFinished("Snyc finished: SUCCESS");
		} catch (Exception e) {
			e.printStackTrace();
			controller.notifySyncFinished("Snyc finished: " + e.getMessage());
		}

	}

}
